#pragma once
#include<iostream>
#include<pthread.h>
//锁不允许拷贝和赋值
namespace MutexModule
{
    class Mutex
    {
    public:
    //锁不允许拷贝和赋值
    Mutex(const Mutex&) = delete;
    const Mutex& operator = (const Mutex&) = delete;

    Mutex()
    {
        int n = ::pthread_mutex_init(&lock,nullptr);
        if(n != 0)
        {
            std::cerr<< "init error" << std::endl;
            exit(1);
        }
    }
    pthread_mutex_t* LockPtr()
    {
        return &lock;
    }
    ~Mutex()
    {
        int n = ::pthread_mutex_destroy(&lock);
        if(n != 0)
        {
            std::cerr<< "destroy error" << std::endl;
            exit(2);
        }
    }

    void Lock()
    {
        int n = ::pthread_mutex_lock(&lock);
        if(n != 0)
        {
            std::cerr<< "lock error" << std::endl;
            exit(3);
        }
    }

    void unlock()
    {
        int n = ::pthread_mutex_unlock(&lock);
        if(n != 0)
        {
            std::cerr<< "unlock error" << std::endl;
            exit(4);
        }
    }

    private:
    pthread_mutex_t lock;

    };
    //类内加锁解锁，减少手动--RAII风格
    class LockGuard
    {
    public:
        LockGuard(Mutex &mtx):_mtx(mtx)
        {
            _mtx.Lock();
        }
        ~LockGuard()
        {
            _mtx.unlock();
        } 
    private:
        Mutex &_mtx;
    };
}